package com.tsj.register;


import com.tsj.common.URL;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author tsj
 * @Date 2023/11/15/16:19
 */
public class MapRemoteRegister {

    private static Map<String, List<URL>> map = new HashMap<>();

    public static void register(String interfaceName,URL url){
        List<URL> urls = map.get(interfaceName);
        if(null == urls){
            urls = new ArrayList<>();
        }
        urls.add(url);
        map.put(interfaceName,urls);

        saveFile();
    }

    public static  List<URL> getUrls(String interfaceName){
        getFile();
        return map.get(interfaceName);
    }

    private static void saveFile(){
        try {
            FileOutputStream outputStream = new FileOutputStream("./temp.txt");
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);
            oos.writeObject(map);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private static void getFile(){
        try {
            FileInputStream inputStream = new FileInputStream("./temp.txt");
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            map =  (Map<String, List<URL>>) objectInputStream.readObject();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
